<template>
	<view>
		<u-tabs :list="tabBars" line-width="120" :scrollable="false" :current="activeTab" @change="changeTab"></u-tabs>
		<view class="content">
			<view class="detail" v-if="showDetail">
				<view v-if="activeTab == 0">
					<defect-content :data="formData" :nfcData="nfcData" :isView="isView"></defect-content>
				</view>
				<view v-if="activeTab == 1">
					<template v-if="!isView">
						<attach-file :attachFile="formData.fileSet" :canEdit="true" @fileSet="fileSet"></attach-file>
					</template>
					<template v-else>
						<attach-file :attachFile="formData.fileSet"></attach-file>
					</template>
				</view>
			</view>
			
			<view>
				<view class="button-groups" v-if="!isView">
					<button type="primary" @click="saveData">{{$t('baseCommon.buttons.save')}}</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import defectContent from "./components/detail-content.vue"
	import attachFile from '@/components/attach-file/attach-file-offline.vue'
	import { notice, utilities, file } from '@/utils/common.js'
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteDefect from '@/utils/business/defectSqlite.js'
	import NFCMixin from '@/utils/business/businessNFC.js'
	
	export default {
		mixins: [
			NFCMixin
		],
		data() {
			return {
				// 流程变量，每个页面必须定义
				formData: {
					analysisTime: "",
					analysiser: "",
					analysiserId: "",
					assetId: "",
					assetName: "",
					assetNo: "",
					assetTypeId: "",
					companyCode: "",
					createTime: "",
					createUser: "",
					dfCategory: "",
					dfClassification: 'fire',
					dfDesp: "",
					dfId: "",
					dfLevelNo: "",
					dfNo: "",
					dfType: "",
					evaluateDesc: "",
					faultReasonDesc: "",
					faultReasonId: "",
					faultSchemeDesc: "",
					faultSchemeId: "",
					faultSymptonDesc: "",
					faultSymptonId: "",
					fileSet: "",
					findTeamName: "",
					findTeamNo: "",
					finddate: "",
					findperson: "",
					findpersonId: "",
					finishTime: "",
					isReplace: 0,
					locaId: "",
					locaNo: "",
					locaName: "",
					manageObjName: "",
					manageObjNo: "",
					mtnPerson: "",
					mtnPersonId: "",
					mtnTeamName: "",
					mtnTeamNo: "",
					noticeperson: "",
					noticepersonId: "",
					oldEqTypeId: "",
					oldEqTypeName: "",
					oldStdWoId: "",
					oldStdWoName: "",
					oldFaultCode: "",
					oldFaultDescription: "",
					oldReasonAnalysis: "",
					oldTreatmentMeasure: "",
					phenomenonId: "",
					phenomenonName: "",
					planEndTime: "",
					remark: "",
					skillNo: "",
					state: "",
					turnFinishTime: "",
					turnLevel: "",
					updateTime: "",
					updateUser: "",
					validateTime: "",
					validateUserId: "",
					validateUserName: "",
					woId: "",
					changeList: []
				},
				// 必须字段end
				tabBars: [
					{ name: this.$t('baseCommon.other.baseInfo'), id: '0' },
					{ name: this.$t('baseCommon.other.attachInfo'), id: '1' }
				],
				activeTab: 0,
				showDetail: false,
				dfId: '',
				dfNo: '',
				source: '',
				sourceId: '',
				sourceData: {},
				sourceType: '',
				isNew: false,
				isEdit: false,
				isView: false,
				nfcData: ''
			}
		},
		components:{
			defectContent,
			attachFile
		},
		onLoad(option) {
			// 先建表，防止报错
			sqliteDefect.createMDfInformation()
			
			// 初始化操作类型
			this.isNew = option.type === "add"
			this.isEdit = option.type === "edit"
			this.isView = option.type === "view"
			
			this.dfId = option.dfId ? option.dfId : ""
			this.dfNo = option.dfNo ? option.dfNo : "" // 主要用于巡检查看缺陷
			this.sourceType = option.sourceType ? option.sourceType : ""
			
			if(option.source){
				this.source = option.source //数据来源
				this.sourceId = option.sourceId //数据来源id
				this.sourceData = JSON.parse(option.sourceData)
			}
			
			this.init()
			
			// #ifdef APP-PLUS
			this.listenNFCStatus()
			this.readyRead = true
			// #endif
		},
		methods: {
			async init() {
				// 创建的话,需要初始化数据
				if (this.isNew) {
					this.formData.state = 'draft'
					this.formData.dfType = '1'
					this.formData.createTime = utilities.getNowDateTime()
					this.formData.createUser = uni.getStorageSync("userId")
					this.formData.finddate = utilities.getNowDateTime()
					this.formData.findperson = uni.getStorageSync("userName")
					this.formData.findpersonId = uni.getStorageSync("userId")
					this.formData.findTeamNo = uni.getStorageSync("userOrgId")
					this.formData.findTeamName = uni.getStorageSync("userOrgName")
					
					switch (this.source) {
						case 'xundianjian': //巡点检
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称
							this.formData.assetId = this.sourceData.assetId //设备资产id
							this.formData.assetNo = this.sourceData.assetNo //设备资产no
							this.formData.assetName = this.sourceData.assetName //设备资产名称
							this.formData.companyCode = this.sourceData.companyCode //场站
							this.formData.fileSet = this.sourceData.attachFile
							this.formData.dfDesp = this.sourceData.dfDesp || '' //缺陷描述
							break;
						case 'woFault': //风机故障登记缺陷
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称	
							this.formData.dfType = this.sourceData.dfType
							this.formData.dfDesp = this.sourceData.dfDesp || '' //缺陷描述
							this.formData.dfLevelNo = this.sourceData.dfLevelNo || '' //缺陷等级
							this.formData.phenomenonId = this.sourceData.phenomenonId || '' //缺陷现象
							this.formData.companyCode = this.sourceData.companyCode || '' //场站
							break;
						case 'sisAlarm': //sis告警信息登记缺陷
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称
							this.formData.dfDesp = this.sourceData.alarmDesc || '' //缺陷描述
							break;
					}
				} else {
					// 缺陷基本信息
					if(this.dfNo) {
						await sqliteUtil.selectTableInfo('m_df_information', 'df_no', this.dfNo).then(res=>{
							utilities.formatHumpLineTransfer(res)
							this.dfId = res[0].dfId
							this.formData = res[0]
						})
					} else {
						await sqliteUtil.selectTableInfo('m_df_information', 'df_id', this.dfId).then(res=>{
							utilities.formatHumpLineTransfer(res)
							this.formData = res[0]
						})
					}
				}
				
				console.log('哈哈哈：', this.sourceData);
				// 页面标题
				uni.setNavigationBarTitle({
				　　title: this.isView ? this.$t('common.buttons.see') : this.$t('defect.state.defReg')
				})
				
				this.showDetail = true
			},
			changeTab(e) {
				this.activeTab = e.index
			},
			saveData() {
				if(!this.validateForm()){
					return;
				}
				
				if(this.isNew) {
					sqliteDefect.insertMDfInformation(this.formData).then(res=>{
						uni.showToast({
							title: this.$t('defect.message.defectRegisterSuccess'),
							duration: 500
						});
						
						if(null !== this.sourceId && '' !== this.sourceId) {
							this.saveSourceData(res)
						}
						
						if(this.source) {
							let data = {
								defectId: res,
								defectLocaId: this.formData.locaId,
								defectLocaNo: this.formData.locaNo,
								defectLocaName: this.formData.locaName,
								defectDesp: this.formData.dfDesp
							}
							const eventChannel = this.getOpenerEventChannel();
							eventChannel.emit('eventData', data);
							uni.navigateBack()
						}
					})
				} else if(this.isEdit) {
					let data = [
						{
							key: "company_code",
							value: this.formData.companyCode,
						},
						{
							key: "df_level_no",
							value: this.formData.dfLevelNo,
						},
						{
							key: "df_type",
							value: this.formData.dfType,
						},
						{
							key: "df_category",
							value: this.formData.dfCategory,

						},
						{
							key: "skill_no",
							value: this.formData.skillNo,
						
						},
						{
							key: "old_fault_description",
							value: this.formData.oldFaultDescription,
						},
						{
							key: "df_desp",
							value: this.formData.dfDesp,
						},
						{
							key: "finddate",
							value: this.formData.finddate,
						},
						{
							key: "plan_end_time",
							value: this.formData.planEndTime,
						},
						{
							key: "attach_file",
							value: files.join(),
						}
					]
					let condition = [
						{
							key: "df_id",
							value: this.dfId
						}
					]
					sqliteUtil.modifyTableInfo('m_df_information', data, condition)
					uni.showToast({
						title: this.$t('defect.message.defectUpdateSuccess'),
						duration: 500
					});
					
					var pages = getCurrentPages()
					var prevPage = pages[pages.length - 2] //上一个页面
					prevPage.$vm.$refs.defect.atTop()
					uni.navigateBack()
				}
			},
			validateForm() {
				var formFlag = true
				if(!this.formData.locaName){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.common.locaName') }))
					formFlag = false
				}
				if(!this.formData.dfLevelNo){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.common.defectLev') }))
					formFlag = false
				}
				if(!this.formData.dfType){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.dfType') }))
					formFlag = false
				}
				if(this.formData.dfType == '2' && !this.formData.dfCategory){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.dfCategory') }))
					formFlag = false
				}
				if(!this.formData.dfDesp){
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('defect.common.defectCom') }))
					formFlag = false
				}
				if(!this.formData.findperson){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.findperson') }))
					formFlag = false
				}
				// if(!this.formData.mtnPerson) {
				// 	notice.toast("请选择消缺负责人")
				// 	formFlag = false
				// }
				// if(!this.formData.oldEqTypeId){
				// 	notice.toast("请选择所属系统")
				// 	formFlag = false
				// }
				// if(!this.formData.phenomenonId){
				// 	notice.toast("请选择缺陷现象")
				// 	formFlag = false
				// }
				
				return formFlag
			},
			saveSourceData(dfId) {
				if('xundianjian' === this.source) { //更新巡点检
					// let data = [
					// 	{
					// 		key: "df_no",
					// 		value: dfId,
					// 	},
					// 	{
					// 		key: "is_abnormal_handled",
					// 		value: 1,
					// 	},
					// 	{
					// 		key: "handling_memo",
					// 		value: this.$t('defect.message.transferredDefect'),
					// 	}
					// ]
					// let condition = [
					// 	{
					// 		key: "id",
					// 		value: this.sourceId
					// 	}
					// ]
					// sqliteUtil.modifyTableInfo('m_ri_task_inspection_abnormal', data, condition)
				}
			},
			fileSet(data) {
				this.formData.fileSet = data
			}
		},
		onBackPress() {
			setTimeout(()=>{
				utilities.backQuick(this.sourceType == 'offline' ? this.sourceType : 'back')
			}, 10);
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/style/common-detail.scss';
	
	.u-tabs {
		background-color: #FFF;
	}
	
	.content {
		background-color: #F1F1F1;
	}
	
	.detail {
		padding-top: 8px;
	}
	
	::v-deep .fileinfo {
		padding: 12px;
	}
</style>
